<template>
  <el-drawer v-model="drawer" title="BANNER编辑" @close="handleClose">
    <ContentBody v-loading="store.updating">
      <el-form
        ref="refBannerForm"
        :model="store.banner"
        :rules="rules"
        label-width="120px"
        style="width: 90%"
        v-if="store.banner"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="store.banner.title" placeholder="请填写标题" />
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="store.banner.link" placeholder="请填写链接" />
        </el-form-item>
        <el-form-item label="BANNER图" prop="cover">
          <ImageUpload v-model="store.banner.cover" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </ContentBody>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useBannerStore } from '@/stores/banner'
import { ElMessage } from 'element-plus'
import ImageUpload from '@/components/upload/single.vue'

const drawer = ref(false)
const store = useBannerStore()
const router = useRouter()
const route = useRoute()
const refBannerForm = ref()
const rules = {
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
  cover: [{ required: true, message: '请选择BANNER图', trigger: 'blur' }],
  link: [{ required: true, message: ' 请填写链接地址', trigger: 'blur' }]
}

const handleClose = () => {
  drawer.value = false
  router.back()
}
const handleSave = () => {
  refBannerForm.value.validate(async (valid: boolean) => {
    if (valid) {
      const result = await store.saveBanner()
      if (result) {
        ElMessage.success('保存成功')
        store.loadBanners()
        router.back()
      }
    }
  })
}

onMounted(() => {
  drawer.value = true
  if (route.params.id) {
    store.loadBanner(parseInt(route.params.id as string))
  } else {
    store.newBanner()
  }
})
</script>
